package com.example.crm.service.impl;

import com.example.crm.mapper.customerMapper;
import com.example.crm.pojo.customer;
import com.example.crm.service.ICustomerService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class CustomerServicelmpl implements ICustomerService {




    SqlSessionFactory sqlSessionFactory;
    {
        // 1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        // 2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);

        //sqlSession = this.sqlSessionFactory.openSession();

        //customerMapper = sqlSession.getMapper(CustomerMapper.class);
    }

    @Override
    public List<customer> findAll() {
        SqlSession sqlSession = this.sqlSessionFactory.openSession();
        customerMapper customerMapper = sqlSession.getMapper(customerMapper.class);
        return customerMapper.selectByExample(null);
    }

    @Override
    public int add(customer customer) {

        SqlSession sqlSession = this.sqlSessionFactory.openSession();
        customerMapper customerMapper = sqlSession.getMapper(customerMapper.class);
        int result = customerMapper.insert(customer);
        //int result=sqlSession.insert("insert", customer);
        System.out.println(customer);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

    @Override
    public int del(long id) {

        SqlSession sqlSession = this.sqlSessionFactory.openSession();
        customerMapper customerMapper = sqlSession.getMapper(customerMapper.class);
        //int result=sqlSession.delete("deleteById", id);
        int result = customerMapper.deleteByPrimaryKey(id);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

    @Override
    public int findById(int id) {
        return 0;
    }
}
